<?php

namespace app\forms\position;

use app\models\Group;
use yii\db\Exception;
use app\forms\Model;
use yii\web\HttpException;
use app\models\Position;
use app\models\Department;
use app\validators\PositiveInteger;

/**
 * 岗位 表单参数
 */
class ParamForm extends Model
{
    public $groupId;
    public $deptId;

    public function rules()
    {
        return [
            ['groupId', PositiveInteger::class],
            ['groupId', 'required'],
            ['groupId', 'exist', 'targetClass' => Group::class, 'targetAttribute' => 'id'],

            ['deptId', PositiveInteger::class],
            ['deptId', 'required'],
            ['deptId', 'exist', 'targetClass' => Department::class, 'targetAttribute' => 'id'],
        ];
    }

    /**
     * @param $param
     * @return array
     * @throws HttpException
     */
    public static function param($param)
    {
        $form = new self;
        $form->setAttributes($param);
        !$form->validate() ? $form->validateError() : '';

        try {
            return (new Position())->getDropList($form['groupId'], $form['deptId']);
        } catch (Exception $e) {
            $form->serverError();
        }
    }
}